package com.example.dormitorymanagement.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.dormitorymanagement.entity.Classmanagement;
import com.example.dormitorymanagement.entity.Student;
import com.example.dormitorymanagement.exception.AbnormalPermissions;
import com.example.dormitorymanagement.mapper.ClassmanagementMapper;
import com.example.dormitorymanagement.mapper.StudentMapper;
import com.example.dormitorymanagement.service.impl.ClassmanagementServiceImpl;
import com.example.dormitorymanagement.service.impl.StudentServiceImpl;
import com.example.dormitorymanagement.service.impl.suthorityservice;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author admin
 * @since 2021-05-31
 */

//@CrossOrigin
@RestController
@RequestMapping("/classmanagement")
@Api(tags = "班级管理，权限低：查询，权限高：增删改查")
public class ClassmanagementController {

    @Autowired
    private ClassmanagementMapper classmanagementMapper;

    @Autowired
    private ClassmanagementServiceImpl classmanagementServiceimpl;

    @Autowired
    private StudentServiceImpl studentserviceimpl;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private com.example.dormitorymanagement.service.impl.suthorityservice suthorityservice;

    @PostMapping(value = "/addormodifyclass")
    @ApiOperation(value = "班级的添加或者修改")
    public Map<String,Object> addclass(@RequestBody Classmanagement classmanagement, HttpServletRequest request) throws AbnormalPermissions {

        Map<String, Object> map = suthorityservice.verification(request);

        if (map.size() != 0)
        {
            return map;
        }

        QueryWrapper<Classmanagement> classmanagementQueryWrapper = new QueryWrapper<>();

        if(classmanagement.getId() != null && classmanagement.getId() != 0 )//id不为null就代表是修改操作
        {
            //修改的的时候，先判断要修改的数值，是否存在，确保护唯一性

            classmanagementQueryWrapper.
                    eq("years",classmanagement.getYears()).
                    eq("academy",classmanagement.getAcademy()).
                    eq("profession",classmanagement.getProfession()).
                    eq("classroom",classmanagement.getClassroom()).
                    eq("counselor",classmanagement.getCounselor());

            Integer result = classmanagementMapper.selectCount(classmanagementQueryWrapper);

            if ( result != 0 )
            {
                map.put("stat",false);

                map.put("message","修改失败，已存在该数据");

                return map;
            }

            classmanagementQueryWrapper.clear();

            classmanagementQueryWrapper.eq("classroom",classmanagement.getClassroom());

            result = classmanagementMapper.selectCount(classmanagementQueryWrapper);

            if ( result != 0 )
            {
                map.put("stat",false);

                map.put("message","修改失败，已经存在该班级");

                return map;
            }

            classmanagementQueryWrapper.clear();

            //判获取这个id原来的数据
            classmanagementQueryWrapper.eq("id",classmanagement.getId());

            Classmanagement originalclass = classmanagementMapper.selectOne(classmanagementQueryWrapper);//这个id原来的班级

            //修改班级的名称才要同步去修改学生的班级名称，同时还要判断，该班级是否有学生，如果有就同步修改，没有就直接修改班级
            if (!classmanagement.getClassroom().equals(originalclass.getClassroom()))
            {

                String banji = (originalclass.getYears() + "").substring(2) + originalclass.getClassroom();//这个是原来的班级

                System.out.println("原来的班级：" + banji);

                classmanagementQueryWrapper.clear();

                QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();

                studentQueryWrapper.eq("student_class",banji);

                if (studentMapper.selectCount(studentQueryWrapper) != 0)
                {

                    //要是不等于0，说明该班级存在，要进行同步修改
                    UpdateWrapper<Student> studentUpdateWrapper = new UpdateWrapper<>();

                    String updateclass = (classmanagement.getYears() + "").substring(2) + classmanagement.getClassroom();

                    System.out.println("要更新的班级：" + updateclass);

                    studentUpdateWrapper.set("student_class",updateclass).eq("student_class",banji);

                    int delete = studentMapper.update(null,studentUpdateWrapper);

                    if (delete != 0)
                    {

                        if (classmanagementServiceimpl.updateById(classmanagement)) {

                            map.put("stat",true);

                            map.put("message","更新成功，连同学生的班级名称一样修改成功");
                            return map;

                        }else {

                            map.put("stat",false);

                            map.put("message","更新失败");
                            return map;

                        }

                    }

                }

                if (classmanagementServiceimpl.updateById(classmanagement)) {

                    map.put("stat",true);

                    map.put("message","更新成功");

                }else {

                    map.put("stat",false);

                    map.put("message","更新失败");

                }

            }

            //修改辅导员，或者直接修改班级名称，不用去同步修改学生里面的人的话，就直接修改就行
            if (classmanagementServiceimpl.updateById(classmanagement)) {

                map.put("stat",true);

                map.put("message","更新成功");

            }else {

                map.put("stat",false);

                map.put("message","更新失败");

            }

            return map;

        }
        System.out.println("进入到这里5");
        classmanagementQueryWrapper.
                eq("years",classmanagement.getYears()).
                eq("academy",classmanagement.getAcademy()).
                eq("profession",classmanagement.getProfession()).
                eq("classroom",classmanagement.getClassroom());


        Integer result = classmanagementMapper.selectCount(classmanagementQueryWrapper);

        if (result == 0) {

            boolean save = classmanagementServiceimpl.save(classmanagement);

            if (save) {
                map.put("stat", true);
                map.put("message", "添加成功");
                return map;
            }

            map.put("stat", false);
            map.put("message", "添加失败，请联系管理员");
            return map;

        }

        System.out.println("进入到这里6");
        map.put("stat", false);
        map.put("message", "添加失败，已存在该班级");

        return map;
    }

    @GetMapping(value = "/getyears")
    @ApiOperation(value = "获取年份")
    public List<Integer> getyears()
    {
        List<Integer> list = new ArrayList<>();

        QueryWrapper<Classmanagement> classmanagementQueryWrapper = new QueryWrapper<>();

        classmanagementQueryWrapper.groupBy("years");

        List<Classmanagement> classmanagements = classmanagementMapper.selectList(classmanagementQueryWrapper);

        classmanagements.forEach(classmanagement -> {
            list.add(classmanagement.getYears());
        });

        return list;
    }

    @GetMapping(value = "/getacademy")
    @ApiOperation(value = "通过年份来获取该年份中所有的学院")
    public List<String> getacademy(@ApiParam(name = "years",value = "年份",required = true) @RequestParam String years)
    {

        List<String> list = new ArrayList<>();

        QueryWrapper<Classmanagement> classmanagementQueryWrapper = new QueryWrapper<>();

        classmanagementQueryWrapper.eq("years",years).groupBy("academy");

        List<Classmanagement> classmanagements = classmanagementMapper.selectList(classmanagementQueryWrapper);

        classmanagements.forEach(classmanagement -> {
            list.add(classmanagement.getAcademy());
        });

        return list;
    }

    @GetMapping(value = "/getprofession")
    @ApiOperation(value = "通过年份，学院来获取该学院下所有的专业")
    public List<String> getprofession(@ApiParam(name = "years",value = "年份",required = true) @RequestParam String years,
                                      @ApiParam(name = "academy",value = "学院",required = true) @RequestParam String academy)
    {
        List<String> list = new ArrayList<>();

        QueryWrapper<Classmanagement> classmanagementQueryWrapper = new QueryWrapper<>();

        classmanagementQueryWrapper.eq("years",years).eq("academy",academy).groupBy("profession");

        List<Classmanagement> classmanagements = classmanagementMapper.selectList(classmanagementQueryWrapper);

        classmanagements.forEach(classmanagement -> {
            list.add(classmanagement.getProfession());
        });

        return list;
    }

    @GetMapping(value = "/getclassroom")
    @ApiOperation(value = "通过年份，学院，专业来获取该专业下的所有班级")
    public List<String> getyear(@ApiParam(name = "years",value = "年份",required = true) @RequestParam String years,
                                @ApiParam(name = "academy",value = "学院",required = true) @RequestParam String academy,
                                @ApiParam(name = "profession",value = "专业",required = true) @RequestParam String profession)
    {
        List<String> list = new ArrayList<>();

        QueryWrapper<Classmanagement> classmanagementQueryWrapper = new QueryWrapper<>();

        classmanagementQueryWrapper.eq("years",years).eq("academy",academy).eq("profession",profession).groupBy("classroom");

        List<Classmanagement> classmanagements = classmanagementMapper.selectList(classmanagementQueryWrapper);

        classmanagements.forEach(classmanagement -> {
            list.add(classmanagement.getClassroom());
        });

        return list;
    }

    @GetMapping(value = "/getstudent")
    @ApiOperation(value = "通过年份，学院，专业，班级来获取该班级下的所有学生以及该班的辅导员")
    public Map<String,Object> getclassroom(@ApiParam(name = "years",value = "年份",required = true) @RequestParam String years,
                                           @ApiParam(name = "academy",value = "学院",required = true) @RequestParam String academy,
                                           @ApiParam(name = "profession",value = "专业",required = true) @RequestParam String profession,
                                           @ApiParam(name = "classroom",value = "班级",required = true) @RequestParam String classroom)
    {
        Map<String,Object> map = new HashMap<>();

        QueryWrapper<Classmanagement> classmanagementQueryWrapper = new QueryWrapper<>();

        classmanagementQueryWrapper.eq("years",years).eq("academy",academy).eq("profession",profession).eq("classroom",classroom);

        classmanagementMapper.selectOne(classmanagementQueryWrapper);

        Classmanagement classmanagement = classmanagementMapper.selectOne(classmanagementQueryWrapper);

        classroom = years.substring(2)+classroom;

        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();

        studentQueryWrapper.eq("student_class",classroom);

        List<Student> students = studentMapper.selectList(studentQueryWrapper);

        map.put("stat",true);

        map.put("counselor",classmanagement.getCounselor());

        map.put("students",students);

        return map;

    }

    @GetMapping(value = "/deleteclass")
    @ApiOperation(value = "删除班级")
    public Map<String,Object> deleteclass(@ApiParam(name = "id",value = "要删除的班级的id",required = true) @RequestParam String id,HttpServletRequest request) throws AbnormalPermissions {

        Map<String, Object> map = suthorityservice.verification(request);

        if (map.size() != 0)
        {
            return map;
        }

        UpdateWrapper<Classmanagement> classmanagementUpdateWrapper = new UpdateWrapper<>();

        classmanagementUpdateWrapper.eq("id",id);

        int delete = classmanagementMapper.delete(classmanagementUpdateWrapper);

        if (delete == 0)
        {

            map.put("stat",false);

            map.put("message","删除失败");

        }else
        {

            map.put("stat",true);

            map.put("message","删除成功");

        }

        return map;

    }

    @GetMapping(value = "/getglassmanagement")
    @ApiOperation(value = "通过条件来获取班级管理对象，默认一页10条数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pc",value = "页数,不传值默认为1"),
            @ApiImplicitParam(name = "years",value = "年份，联合查询条件"),
            @ApiImplicitParam(name = "academy",value = "学院，联合查询条件"),
    })
    public Map<String,Object> getglassmanagement(Integer pc,String years,String academy)
    {
        Map<String,Object> map = new HashMap<>();
        if (pc == null)
        {
            pc = 1;
        }

        QueryWrapper<Classmanagement> classmanagementQueryWrapper = new QueryWrapper<>();

        Map<String,Object> classquery = new HashMap<>();

        classquery.put("years",years);
        classquery.put("academy",academy);

        classmanagementQueryWrapper.allEq(classquery,false);

        Page<Classmanagement> classmanagementPage = new Page<>(pc,10);

        classmanagementMapper.selectPage(classmanagementPage,classmanagementQueryWrapper);

        if ( pc > classmanagementPage.getPages())
        {
            map.put("stat",false);

            map.put("message","页数越界，总页数：" + classmanagementPage.getPages() + "，当前页数:" + classmanagementPage.getCurrent());

            return map;
        }

        map.put("stat",true);
        map.put("classmanagement", classmanagementPage.getRecords());
        map.put("pages",classmanagementPage.getPages());
        map.put("page",classmanagementPage.getCurrent());
        map.put("total", classmanagementPage.getTotal());
        map.put("current", classmanagementPage.getCurrent());
        map.put("hasPrevious",classmanagementPage.hasPrevious());
        map.put("hasNext",classmanagementPage.hasNext());

        return map;
    }



}

